import random
from multiprocessing.pool import ThreadPool, IMapIterator
import time
from typing import List
from common.utility import Utility
import threading

# 主函数
def main(thread_count: int = 5, ordered: bool = True):
    Utility.print_info('entered.')
    with ThreadPool(initializer=threadpool_init) as pool:
        sleep_time_list: List[int] = []
        for i in range(thread_count):
            sleep_time_list.append(random.randint(1,10))
        results: IMapIterator[tuple[int, str, int]]
        if ordered:
            results = pool.imap(task, sleep_time_list)
        else:
            results = pool.imap_unordered(task, sleep_time_list)
        for result in results:
            Utility.print_info(f'线程池返回值：{result}')
    Utility.print_info('exited.')

# 线程池初始化
def threadpool_init() -> None:
    Utility.print_info('线程池初始化。')

# 任务
def task(sleep_time: int) -> tuple[int, str, int]:
    Utility.print_info(f'entered. It will sleep {sleep_time} seconds.')
    time.sleep(sleep_time)
    Utility.print_info('exited.')
    cur_thread: threading.Thread = threading.current_thread()
    return cur_thread.ident, cur_thread.name, sleep_time

main(2, ordered=False)
